﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Ionic.Zip;

namespace Flower.Directory.Management
{
    internal class ZipFileDirectoryImportSource : IDirectoryImportSource
    {
        private readonly ZipFile _zipFile;

        public ZipFileDirectoryImportSource(ZipFile zipFile)
        {
            _zipFile = zipFile;
        }

        private static string TransformPath(string path)
        {
            return
                ((path.Length > 0 && path[0] == '\\') ? path.Substring(1) : path)
                    .Replace('\\', '/');
        }

        public bool FileExists(string path)
        {
            return _zipFile.ContainsEntry(TransformPath(path));
        }

        public bool DirectoryExists(string path)
        {
            return _zipFile.ContainsEntry(TransformPath(path) + "/");
        }

        public T ReadFile<T>(string path, Func<Stream, T> readAction)
        {
            lock (_zipFile)
            {
                using (var stream = _zipFile[TransformPath(path)].OpenReader())
                {
                    return readAction(stream);
                }
            }
        }

        public IEnumerable<string> EnumerateFiles(string path, string pattern)
        {
            return _zipFile.SelectEntries(pattern, TransformPath(path)).Select(ent => ent.FileName);
        }
    }
}
